﻿using System;
using System.IO;
using System.Xml;
using System.Web;

namespace AppEntity
{
    public class GlobalCache    
    {               
        public static XmlDocument GetGlobalConfig()
        {
            string siteconfig = String.Empty;
            if (HttpContext.Current != null)
            {
                siteconfig = Path.GetFullPath(HttpContext.Current.Server.MapPath("/") + "../global.config");
            }
            else
            {
                string appfolder = AppDomain.CurrentDomain.BaseDirectory;
                if (File.Exists(appfolder + "global.config"))
                {
                    siteconfig = appfolder + "global.config";
                }
                else
                {
                    DirectoryInfo parent = new DirectoryInfo(appfolder);
                    if (File.Exists(parent.Parent.FullName + "\\global.config"))
                    {
                        siteconfig = parent.Parent.FullName + "\\global.config";
                    }
                    else
                    {
                        throw new NullReferenceException("Can not found site.config at the same folder or parent!");
                        return null;
                    }
                }
                
            }
            if (HttpRuntime.Cache[siteconfig] != null)
            {
                return (XmlDocument)HttpRuntime.Cache[siteconfig];
            }
            XmlDocument dom = new XmlDocument();
            dom.Load(siteconfig);            
            System.Web.Caching.CacheDependency dep = new System.Web.Caching.CacheDependency(siteconfig);
            HttpRuntime.Cache.Insert(siteconfig, dom, dep, System.DateTime.Now.AddHours(24), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null);
            return (XmlDocument)HttpRuntime.Cache[siteconfig];
        }
        
    }
}
